import json
import uuid
from datetime import datetime
from flask import g, jsonify
from flask import request
from flask_jwt_extended import jwt_required, current_user
from sqlalchemy import asc, desc
from myapp import db
from myapp.routes import system
from myapp.models import Resource, ResourceType, Organization, Role, User
from myapp.utils.auth import permission

@permission('system:menu:list')
@system.route('/menu/list', methods=['GET'])
@jwt_required()
def syresource_treeGrid():
    filters = []
    if 'menuName' in request.args:
        filters.append(Resource.name.like('%' + request.args['menuName'] + '%'))

    order_by = []
    order_by.append(asc(getattr(Resource, 'resource_id')))
    order_by.append(asc(getattr(Resource, 'seq')))

    res_list = Resource.query.filter(*filters).order_by(*order_by)

    return jsonify({"msg":"操作成功","code":200, "data": [org.to_json() for org in res_list]})

@permission('system:menu:query')
@system.route('/menu/<id>', methods=['GET'])
@jwt_required()
def syresource_getById(id):
    res = Resource.query.get(id)

    if res:
        return jsonify({'code': 200, 'msg': '操作成功', 'data': res.to_json()})
    else:
        return jsonify({'success': False, 'msg': 'error'})

@permission('system:menu:edit')
@system.route('/menu', methods=['PUT'])
@jwt_required()
def syresource_update():
    res = Resource.query.get(request.json['menuId'])

    res.update_time = datetime.now()
    if 'icon' in request.json: res.iconcls = request.json['icon']
    if 'component' in request.json: res.url = request.json['component']
    if 'path' in request.json: res.path = request.json['path']
    if 'menuName' in request.json: res.name = request.json['menuName']
    if 'orderNum' in request.json: res.seq = request.json['orderNum']
    if 'perms' in request.json: res.perms = request.json['perms']
    if 'menuType' in request.json: res.resource_type_id = '1' if request.json['menuType'] == 'F' else '0' if request.json['menuType'] == 'C' else '3'
    if 'parentId' in request.json: 
        parent = Resource.query.get(str(request.json['parentId']))
        if parent: res.parent = parent
    if 'status' in request.json: res.status = request.json['status']

    db.session.add(res)

    return jsonify({'code': 200, 'msg': '操作成功'})

@permission('system:menu:add')
@system.route('/menu', methods=['POST'])
@jwt_required()
def syresource_save():
    res = Resource()

    res.ID = str(uuid.uuid4())
    if 'icon' in request.json: res.iconcls = request.json['icon']
    if 'component' in request.json: res.url = request.json['component']
    if 'path' in request.json: res.path = request.json['path']
    if 'menuName' in request.json: res.name = request.json['menuName']
    if 'orderNum' in request.json: res.seq = request.json['orderNum']
    if 'perms' in request.json: res.perms = request.json['perms']
    if 'menuType' in request.json: res.resource_type_id = '1' if request.json['menuType'] == 'F' else '0' if request.json['menuType'] == 'F' else '3'
    if 'parentId' in request.json: 
        parent = Resource.query.get(str(request.json['parentId']))
        if parent: res.parent = parent
    if 'status' in request.json: res.status = request.json['status']

    db.session.add(res)

    return jsonify({'code': 200, 'msg': '操作成功'})

@permission('system:menu:remove')
@system.route('/menu/<id>', methods=['DELETE'])
@jwt_required()
def syresource_delete(id):
    res = Resource.query.get(id)
    if res:
        db.session.delete(res)

    return jsonify({'code': 200, 'msg': '操作成功'})

@system.route('/menu/treeselect', methods=['GET'])
@jwt_required()
def syresource_tree_select():
    resList = Resource.query.filter(Resource.resource_id == None)

    return jsonify({'msg': '操作成功', 'code': 200, "data": [res.to_tree_select_json() for res in resList]})

@system.route('/menu/roleMenuTreeselect/<roleId>', methods=['GET'])
@jwt_required()
def syresource_role_tree_select(roleId):
    role = Role.query.get(roleId)
    resList = Resource.query.filter(Resource.resource_id == None)

    return jsonify({'msg': '操作成功', 'code': 200, \
        "menus": [res.to_tree_select_json() for res in resList], \
        "checkedKeys": [res.ID for res in role.resources]}) 

